<?php

namespace common\models\c2\entity;

use cza\base\models\statics\ImageSize;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\c2\statics\TopicArticleType;
use cza\base\models\statics\EntityModelStatus;

/**
 * This is the model class for table "{{%topic_article}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $title
 * @property string $meta_title
 * @property string $meta_keywords
 * @property string $meta_description
 * @property string $summary
 * @property string $content
 * @property integer $author_id
 * @property string $author_name
 * @property integer $views_count
 * @property integer $comment_count
 * @property string $released_at
 * @property integer $is_shared
 * @property string $created_by
 * @property string $updated_by
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class TopicArticle extends \cza\base\models\ActiveRecord {

//    public $topic_ids;

    use \common\traits\AttachmentTrait;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%topic_article}}';
    }
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
                    'contentBehavior' => [
                        'class' => \common\behaviors\CmsContentBehavior::className(),
                        'fields' => ['content'],
                        'config' => [
                            'entity_class' => TopicArticle::className()
                        ],
                        'options' => [
                            'renderWhenAttach' => false,
                            'renderWhenAfterFind' => true,
                            'renderImage' => true,
                            'renderBlock' => false,
                            'renderWidget' => false,
                            'renderAlbumBlock' => false,
                            'renderInternal' => false,
                        ],
                    ],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['type', 'author_id', 'views_count', 'comment_count', 'is_shared', 'is_released', 'created_by', 'updated_by', 'status', 'position'], 'integer'],
            [['meta_keywords', 'meta_description', 'summary', 'content'], 'string'],
            [['released_at', 'created_at', 'updated_at', 'topic_ids'], 'safe'],
            [['title', 'content', 'author_name'], 'required'],
            [['title', 'meta_title', 'author_name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'title' => Yii::t('app.c2', 'Title'),
            'meta_title' => Yii::t('app.c2', 'Meta Title'),
            'meta_keywords' => Yii::t('app.c2', 'Meta Keywords'),
            'meta_description' => Yii::t('app.c2', 'Meta Description'),
            'summary' => Yii::t('app.c2', 'Summary'),
            'content' => Yii::t('app.c2', 'Content'),
            'author_id' => Yii::t('app.c2', 'Author ID'),
            'author_name' => Yii::t('app.c2', 'Author Name'),
            'views_count' => Yii::t('app.c2', 'Views Count'),
            'comment_count' => Yii::t('app.c2', 'Comment Count'),
            'released_at' => Yii::t('app.c2', 'Released At'),
            'is_released' => Yii::t('app.c2', 'Is Released'),
            'is_shared' => Yii::t('app.c2', 'Is Shared'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
            'topic_ids' => Yii::t('app.c2', 'Topic'),
            'avatar' => Yii::t('app.c2', 'Avatar'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\TopicArticleQuery the active query used by this AR class.
     */
    public static function find() {
        return new \common\models\c2\query\TopicArticleQuery(get_called_class());
    }

    /**
     * setup default values
     * */
    public function loadDefaultValues($skipIfSet = true) {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getDetailUrl() {
        if (!isset($this->_data['DETAIL_URL'])) {
            $this->_data['DETAIL_URL'] = FRONTEND_BASE_URL . "/study/detail/id/" . $this->id;
        }
        return $this->_data['DETAIL_URL'];
    }

    public function getTypeLabel() {
        return TopicArticleType::getLabel($this->type);
    }

    public function getTypeUrl() {
        if ($this->type == TopicArticleType::TYPE_WECHAT) {
            return TopicArticleWechat::className();
        } else {
            return TopicArticle::className();
        }
    }

    public function getThumbnailUrl($attribute = 'avatar') {
        return $this->getImageUrl($attribute, ImageSize::THUMBNAIL);
    }

    public function getIconUrl($attribute = 'avatar') {
        return $this->getImageUrl($attribute, ImageSize::ICON);
    }

    public function getMediumUrl($attribute = 'avatar') {
        return $this->getImageUrl($attribute, ImageSize::MEDIUM);
    }

    public function getOriginalUrl($attribute = 'avatar') {
        return $this->getImageUrl($attribute, ImageSize::ORGINAL);
    }

    public function getImageUrl($attribute = 'avatar', $size = ImageSize::THUMBNAIL) {
        $key = $attribute . '_' . $size;
        if (!isset($this->_data[$key])) {
            $attachment = $this->getAttachmentImage($attribute);
            $this->_data[$key] = !is_null($attachment) ? $attachment->getUrlByFormat($size) : "";
        }
        return $this->_data[$key];
    }

    public function beforeSave($insert) {
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public function getAllAttachments() {
        $condition = ['entity_class' => TopicArticle::className()];
        return $this->hasMany(EntityAttachmentImage::className(), ['entity_id' => 'id'])
                        ->andOnCondition($condition)
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

    public function getAttachmentImages($attribute = 'album') {
        $condition = !empty($attribute) ? ['entity_class' => TopicArticle::className(), 'entity_attribute' => $attribute, 'status' => EntityModelStatus::STATUS_ACTIVE] : ['entity_class' => BaseModel::className(), 'status' => EntityModelStatus::STATUS_ACTIVE];
        return $this->hasMany(EntityAttachmentImage::className(), ['entity_id' => 'id'])
                        ->andOnCondition($condition)
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

    public function getAttachmentFiles($attribute = 'files') {
        return $this->hasMany(EntityAttachmentFile::className(), ['entity_id' => 'id'])
                        ->andOnCondition(['entity_class' => TopicArticle::className(), 'entity_attribute' => $attribute, 'status' => EntityModelStatus::STATUS_ACTIVE])
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

    public function getTopics() {
        return $this->hasMany(Topic::className(), ['id' => 'topic_id'])
            ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->viaTable('{{%topic_article_rs}}', ['article_id' => 'id']);
    }

}
